import { defineStore } from "pinia";
import { buyProducts, IPdroduct } from "../api/shop";
import {useProductStore} from './products'
type cartProduct = {
    quantity : number
} & Omit<IPdroduct,'inventory'>

export const useCartStore = defineStore('cart',{
    state: () =>{
        return {
            cartProducts:[] as cartProduct[],
            checkoutStatus : null as null | string
        }
    },

    getters:{
        totalPrice(state){
            return state.cartProducts.reduce((total,item) => {
                return total + item.price * item.quantity 
            },0)
        }
    },
    actions:{
        addProductToCart(product:IPdroduct){
            /**
             * 要求: 
             * 1.看商品有没有库存
             * 2.检查购物车是否有该商品，
             * 3.有购物车数量+1，如果没有，添加到购物车
             * 4. 更新商品库存
             *  */ 
            // console.log("addProductTpcart",product);
            if(product.inventory < 1){
                return
            }
            const cartItem = this.cartProducts.find(item => item.id === product.id)
            if(cartItem ){
                cartItem.quantity++
            } else {
                this.cartProducts.push({
                    id : product.id,
                    title : product.title,
                    price : product.price,
                    quantity : 1

                })
            }
            const productStore = useProductStore()
            productStore.decrementProduct(product)
        },

        async checkout(){
            const ret = await buyProducts()
            this.checkoutStatus = ret ? "成功" : "失败"
            if(ret){
                this.cartProducts = []
            }
        }
    }
})